package com.itheima.filter;

import com.itheima.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求url,httpServletRuest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        if (url.toString().contains("login")){
            //判断请求url中是否包含login,如果包含,说明是登录请求
            filterChain.doFilter(servletRequest,servletResponse);
        }
        //获取请求头中的令牌(token)
        String token = request.getHeader("token");
        //判断令牌是否存在,如果不存在,响应401
        if (token == null){
            response.setStatus(401);
            return;//不能忘记返回
        }
        //解析token,如果解析失败,响应401
        try {
            JwtUtils.parseJWT(token);
            filterChain.doFilter(servletRequest,servletResponse);
        } catch (Exception e) {
            response.setStatus(401);
            return;
        }
    }
}
